import axios from "axios";
import { Message } from "element-ui";
// import store from "@/store";
import { getToken } from "@/utils/auth";

// create an axios instance
const service = axios.create({
  baseURL: "https://www.fastmock.site/mock/82b2526621aa2bce3050100005312a47/xj",
  timeout: 5000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers["X-Token"] = getToken();
    }
    return config;
  },
  error => {
    console.log(error);
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data;
    return res;
  },
  error => {
    console.log("err" + error);
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

// 封装get请求
export function get(url, params = {}) {
  params.t = new Date().getTime(); // get方法加一个时间参数,解决ie下可能缓存问题.
  return service({
    url: url,
    method: "get",
    params
  });
}

// 封装post请求
export function post(url, data = {}) {
  // 默认配置
  let sendObject = {
    url: url,
    method: "post",
    data: data
  };
  sendObject.data = JSON.stringify(data);
  return service(sendObject);
}

export default service;
